/*
 *  libKara - Library for basic instant messaging functions
 *  Copyright (C) 2007 Markus Karnik
 *
 *  This program is free software; you can redistribute it and/or modify it 
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 3 of the License, 
 *  or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 *  for more details.
 *
 *  You should have received a copy of the GNU General Public License along 
 *  with this program; if not, see <http://www.gnu.org/licenses/>.
 *  
 */
package de.karnik.libkara.proto.xmpp.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;

import de.karnik.libkara.proto.xmpp.XmppBufferedReader;
import de.karnik.libkara.proto.xmpp.XmppBufferedWriter;
import de.karnik.libkara.proto.xmpp.XmppSettings;
import de.karnik.libkara.proto.xmpp.net.secure.ServerTrustManager;

/**
 * The xmpp connection manager class.
 * 
 * @author Markus Karnik - markus.karnik@my-design.org
 * @version 1.0
 * @since 1.0
 */
public class XmppConnectionManager {
	
	/**
	 * The XMPP buffered writer.
	 */
	private XmppBufferedWriter xmppWriter = null;
	/**
	 * The XMPP buffered reader.
	 */
	private XmppBufferedReader xmppReader = null;
	/**
	 * The client socket.
	 */
	private Socket socket = null;
	/**
	 * The XMPP settings object.
	 */
	private XmppSettings xmppSettings = null;
	/**
	 * Compression enabled indicator. 
	 */
	private boolean compressionEnabled = false;
	
	/**
	 * Constructs a XMPP connection manager with the given XMPP settings.
	 * 
	 * @param xmppSettings The XMPP settings with username, password and host.
	 */
	public XmppConnectionManager( XmppSettings xmppSettings ) {
		this.xmppSettings = xmppSettings;
	}
	
	/**
	 * Disconnects the protocol.
	 * 
	 * @throws IOException
	 */
	public void disconnect() throws IOException {
		xmppReader.close();
		xmppWriter.close();
		socket.close();
		
		xmppReader = null;
		xmppWriter = null;
		socket = null;
	}
	
	/**
	 * Sets the XMPP settings.
	 * 
	 * @param xmppSettings The XMPP settings to set.
	 */
	public void setXmppSettings( XmppSettings xmppSettings ) {
		this.xmppSettings = xmppSettings;	
	}
	
	/**
	 * Connect the protocol.
	 * 
	 * @throws UnknownHostException
	 * @throws IOException
	 */
	public void connect() throws UnknownHostException, IOException {
		socket = new Socket( xmppSettings.getStringData( XmppSettings.STRING_VALUE_HOSTNAME), 
							 xmppSettings.getIntegerData( XmppSettings.INTEGER_VALUE_PORT ) );

		compressionEnabled = false;
		initIO();
	}
	
	/**
	 * Refreshes I/O streams.
	 * 
	 * @throws IOException
	 */
	public void refreshIO() throws IOException {
		initIO();
	}
	
	/**
	 * Initiate the I/O streams.
	 * 
	 * @throws IOException
	 */
	public void initIO() throws IOException {
		compressionEnabled = false;
		if( !isCompressionEnabled() ) {
			xmppWriter = new XmppBufferedWriter( new OutputStreamWriter( socket.getOutputStream(), "UTF-8" ) );
			xmppReader = new XmppBufferedReader( new InputStreamReader( socket.getInputStream(), "UTF-8" ) );
		} else {
			// TODO Enbale Compression
		}
	}

	/**
	 * Returns the connection indicator.
	 * 
	 * @return <b>true</b> if protocol is connected, <b>false</b> otherwise.
	 */
	public boolean isConnected() {
		if( socket != null ) {
			// TODO BUG???
			if( socket instanceof SSLSocket )
				return true;
			else
				return socket.isConnected();
		}
		
		return false;
	}

	/**
	 * Returns the compression enabled indicator.
	 * 
	 * @return <b>true</b> if compression is enabled, <b>false</b> otherwise.
	 */
	public boolean isCompressionEnabled() {
		return compressionEnabled;
	}

	/**
	 * Sets the compression enabled indicator.
	 * 
	 * @param compressionEnabled <b>true</b> if compression is enabled, <b>false</b> otherwise.
	 */
	public void setCompressionEnabled(boolean compressionEnabled) {
		this.compressionEnabled = compressionEnabled;
	}


	/**
	 * Returns the XMPP reader.
	 * 
	 * @return The XMPP reader.
	 */
	public BufferedReader getXmppReader() {
		return xmppReader;
	}


	/**
	 * Returns the XMPP writer.
	 * 
	 * @return The XMPP writer.
	 */
	public BufferedWriter getXmppWriter() {
		return xmppWriter;
	}
	
	
	// =================================================== TLS ============================
	
	/**
	 * Starts the TLS negotation. Creates a secured connection.
	 * 
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 * @throws IOException
	 */
	public void startTLSNegotation() throws NoSuchAlgorithmException, KeyManagementException, IOException {
       

		SSLContext context = SSLContext.getInstance( "TLS" );

		context.init( null,
			        	new javax.net.ssl.TrustManager[]{ new ServerTrustManager() },
			        	new java.security.SecureRandom());
        
        Socket plain = socket;
        
        
         socket = context.getSocketFactory().createSocket( plain,
        												 plain.getInetAddress().getHostName(), 
        												 plain.getPort(), 
        												 true );
       
        refreshIO();
        ( ( SSLSocket ) socket).startHandshake();
        
        xmppSettings.putBooleanData( XmppSettings.BOOLEAN_VALUE_TLS_ESTABLISHED, true );
        
	}


	/**
	 * Returns the XMPP settings.
	 * 
	 * @return The XMPP settings.
	 */
	public XmppSettings getXmppSettings() {
		return xmppSettings;
	}
	
	
}
